#! /usr/bin/env python
# -*- coding: utf8 -*-

import sys

if sys.version_info[:2] == (2, 5):
    from xml.etree import cElementTree as et
else:
    import cElementTree as et
import zope.interface
import random

import base
from sys import stderr

if __name__ == '__main__':
    import sys
    print "You shouldn't be running this file!"
    sys.exit()

class addChildren(object):
    zope.interface.implements(base.IAlgorithm)
    name = "addChildren"

    def __init__(self, node):
        self.__names  = []
        self.__single = False

        self.__path = base.parser(node.find("./parameters/path").text.strip())

    def __call__(self, node, parentMap, root):
        first_name = self.__path[0]
        if type(first_name) == list:
            first_name = random.choice(first_name)

        first = maisNovo = et.Element(first_name)
        parentMap[maisNovo] = node

        for i in self.__path[1:]:
            if type(i) == list:
                i = random.choice(i)

            if i == '-':
                continue

            newElement = et.Element(i)
            maisNovo.append(newElement)
            parentMap[newElement] = maisNovo
            maisNovo = newElement


        nodes = node[:]

        for i in nodes:
            node.remove(i)
            maisNovo.append(i)
            parentMap[i] = maisNovo

        if node.text != None and len(node.text.strip()) > 0:
            maisNovo.text = node.text
            node.text = None

        node.append(first)

__plugins__ = (addChildren, )
